const jwt = require("jsonwebtoken");
const { PRIVATE_KEY } = require("../app/config");
const { logger } = require("../../logger");

class AuthController {
  async login(ctx, next) {
    try {
      // 这user是result，从数据库读出来的
      const { id, username, permission } = ctx.user;
      // 登录成功后生成token
      const token = jwt.sign({ id, username, permission }, PRIVATE_KEY, {
        // 设置过期时间
        expiresIn: 60 * 60 * 24,
        // 加密算法
        algorithm: "RS256",
      });
      ctx.body = {
        code: 200,
        message: "登录成功",
        data: { token, user: ctx.user },
      };
    } catch (error) {
      logger.error(error);
      console.log(error);
    }
  }

  async success(ctx, next) {
    ctx.success("授权成功");
  }
}

module.exports = new AuthController();
